package com.gs.netty.core.resolver.args;

import org.springframework.core.MethodParameter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 抽象的参数解析器
 * @param <Request>
 */

public  abstract class AbstractHandlerMethodArgumentResolver<Request> implements HandlerMethodArgumentResolver<Request> {


   protected final List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>();

    protected final Map<MethodParameter, HandlerMethodArgumentResolver> argumentResolverCache =
            new ConcurrentHashMap<>(256);


    @Override
    public boolean supportsParameter(MethodParameter parameter) {

        return getArgumentResolver(parameter) != null;
    }

    protected HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) {
        HandlerMethodArgumentResolver result = this.argumentResolverCache.get(parameter);
        if (result == null) {
            for (HandlerMethodArgumentResolver resolver : this.argumentResolvers) {

                if (resolver.supportsParameter(parameter)) {
                    result = resolver;
                    this.argumentResolverCache.put(parameter, result);
                    break;
                }
            }
        }
        return result;
    }

    protected HandlerMethodArgumentResolver addArgumentResolvers(HandlerMethodArgumentResolver... resolvers) {
        argumentResolvers.addAll(Arrays.asList(resolvers));
        return this;
    }

    protected HandlerMethodArgumentResolver addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        argumentResolvers.addAll(resolvers);
        return this;
    }

}
